<?php

namespace App\Admin\Override\Field;

use App\Models\Attachements;
use Dcat\Admin\Form\Field\File;
use Dcat\Admin\Support\Helper;

class MultipleFileView extends File
{
    protected $view = 'files.file';

    /**
     * Allow to sort files.
     *
     * @param  bool  $value
     * @return $this
     */
    public function sortable(bool $value = true)
    {
        $this->options['sortable'] = $value;

        return $this;
    }

    /**
     * Set a limit of files.
     *
     * @param  int  $limit
     * @return $this
     */
    public function limit(int $limit)
    {
        if ($limit < 2) {
            return $this;
        }
        $this->options['fileNumLimit'] = $limit;

        return $this;
    }

    /**
     * Prepare for saving.
     *
     * @param  string|array  $file
     * @return array
     */
    protected function prepareInputValue($file)
    {
        if ($path = request(static::FILE_DELETE_FLAG)) {
            $this->deleteFile($path);

            return array_values(array_diff($this->original, [$path]));
        }

        $file = Helper::array($file, true);

        $this->destroyIfChanged($file);

        return $file;
    }

    protected function forceOptions()
    {
    }

    protected function initialPreviewConfig(): array
    {
        $previews = [];
        foreach (Helper::array($this->value()) as $path){
            $fileName[] = pathinfo($path)['filename'];
        }
        $attach = Attachements::query()->whereIn('md5_name', $fileName ?? [])->get()->toArray();
        foreach ($attach as $value) {
            $previews[] = [
                'id'   => $value['path'],
                'path' => Helper::basename($value['real_name']),
                'url'  => $this->objectUrl($value['path']),
            ];
        }

        return $previews;
    }
}
